package com.mfnote.view.setting;

import com.mfnote.view.R;
import com.mfnote.view.R.drawable;
import com.mfnote.view.R.id;
import com.mfnote.view.R.layout;
import com.mfnote.view.hand.HandWritingActivity;
import com.mfnote.view.main.MainActivity;
import com.mfnote.view.other.MyApplication;
import com.mfnote.view.paint.NewPaintActivity;
import com.mfnote.view.record.NewRecordActivity;
import com.mfnote.view.setting.ShakeListener.OnShakeListener;
import com.mfnote.view.setting.SlipButton.OnChangedListener;
import com.mfnote.view.write.NewWriteActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class SettingActivity extends Activity implements OnClickListener,
		OnChangedListener {

	ImageButton btn_back;
	RelativeLayout ll_encypt, ll_desk_widget, ll_shake_new, ll_photo,
			ll_clear_data, ll_about;
	public String filePath = Environment.getExternalStorageDirectory()
			.getAbsolutePath(); //SD卡路径
	public String[] fileName = new String[] { "record", "image", 
			"notes", "hand" }; //SD卡MFNote文件夹下的四个子文件
	private AlertDialog alertDlgClear; //一键清除数据提示框
	
	/******************摇一摇新建************/
	ShakeListener mShakeListener = null; //自定义监听器
	private SlipButton slipButton; //自定义滑动按钮控件
	public static boolean mCheckState; //保存开关状态

	private List<Boolean> listItem = new ArrayList<Boolean>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);
		MyApplication.getInstance().addActivity(this);

		btn_back = (ImageButton) findViewById(R.id.set_btn_back);
		ll_encypt = (RelativeLayout) findViewById(R.id.set_encypt);
		ll_desk_widget = (RelativeLayout) findViewById(R.id.set_desk_widget);
		ll_shake_new = (RelativeLayout) findViewById(R.id.set_shake_new);
		ll_photo = (RelativeLayout) findViewById(R.id.set_photo);
		ll_clear_data = (RelativeLayout) findViewById(R.id.set_clear_data);
		ll_about = (RelativeLayout) findViewById(R.id.set_about);

		btn_back.setOnClickListener(this);
		ll_encypt.setOnClickListener(this);
		ll_desk_widget.setOnClickListener(this);
		ll_shake_new.setOnClickListener(this);
		ll_photo.setOnClickListener(this);
		ll_clear_data.setOnClickListener(this);
		ll_about.setOnClickListener(this);

		/** 摇一摇新建 **/
		mShakeListener = new ShakeListener(this);
		slipButton = (SlipButton) findViewById(R.id.slipButton);
		slipButton.SetOnChangedListener("the one", this);

		slipButton.setChecked(mCheckState);// 设置button的初始化状态为打开
		
		//
		listItem.add(0, false);
		listItem.add(1, false);
		listItem.add(2, false);
		listItem.add(3, false);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.set_btn_back: // 返回到主界面
			Intent intent1 = new Intent(this, MainActivity.class);
			startActivity(intent1);
			finish();
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
			break;
		case R.id.set_encypt: // 加密
			Intent intent2 = new Intent(this, EncyptActivity.class);
			startActivity(intent2);
			finish();
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_left_out);
			break;
		case R.id.set_desk_widget: // 生成桌面插件
			showSHortCutDialog();
			//Toast.makeText(this, "生成桌面插件", Toast.LENGTH_SHORT).show();
			break;
		case R.id.set_shake_new: // 摇一摇新建记事
			// Toast.makeText(this, "摇一摇新建记事", Toast.LENGTH_SHORT).show();

			// setShakeNew();

			break;
		case R.id.set_photo: // 查看本地文件
			//Toast.makeText(this, "进入MFNote相册", Toast.LENGTH_SHORT).show();
			boolean sdcardExist = Environment.getExternalStorageState()
			.equals(android.os.Environment.MEDIA_MOUNTED);
			if (!sdcardExist) {
				Toast.makeText(this, "未找到SD卡",
						Toast.LENGTH_SHORT).show();
			}
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("file/*");
			startActivity(Intent.createChooser(intent, null));
			break;
		case R.id.set_clear_data: // 一键清除数据
			showClearDialog();
			break;
		case R.id.set_about: // 关于
			Intent intent3 = new Intent(this, AboutActivity.class);
			startActivity(intent3);
			finish();
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_left_out);
			break;
		}
	}

	/** 一键清除数据提示对话框 */
	private void showClearDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_set_clearall, null);
		alertDlgClear = new AlertDialog.Builder(this).create();
		alertDlgClear.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgClear.setContentView(viewDialog, layoutParams);
		Button btn_clear=(Button) viewDialog.findViewById(R.id.set_clear_sure);
		Button btn_cancel=(Button) viewDialog.findViewById(R.id.set_clear_cancel);
		btn_clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgClear.dismiss();
				File f=new File(filePath+"/MFNote");
				if(f.exists()){
					for(int i=0;i<fileName.length;i++){
						File file=new File(filePath+"/MFNote/"+fileName[i]);
						clearAllDada(file);
					}
					Toast.makeText(SettingActivity.this, "清除数据成功", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(SettingActivity.this, "文件不存在",Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgClear.dismiss();
			}
		});
	}
	
	/** 一键清除数据 */
	private void clearAllDada(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					clearAllDada(files[i]);
				}
			}
			file.delete();
		} 
	}

	/** 快捷方式对话框 **/
	private void showSHortCutDialog() {
		final AlertDialog builder = new AlertDialog.Builder(this).create();

		builder.show();
		LayoutInflater inflater = LayoutInflater.from(this);
		View viewDialog = inflater.inflate(R.layout.shortcut_dialog, null);
		Display display = this.getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();
		LayoutParams layoutParams = new LayoutParams(width * 90 / 100,
				height * 70 / 100);
		builder.setContentView(viewDialog, layoutParams);

		final ListView lv = (ListView) viewDialog
				.findViewById(R.id.lv_shortcut_item);

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("name", "文字");
		map1.put("checked", false);
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("name", "笔迹");
		map2.put("checked", false);
		Map<String, Object> map3 = new HashMap<String, Object>();
		map3.put("name", "录音");
		map3.put("checked", false);
		Map<String, Object> map4 = new HashMap<String, Object>();
		map4.put("name", "涂鸦");
		map4.put("checked", false);
		list.add(map1);
		list.add(map2);
		list.add(map3);
		list.add(map4);
		SimpleAdapter adapter = new SimpleAdapter(this, list,
				R.layout.shortcut_item, new String[] { "name", "checked" },
				new int[] { R.id.tv_shortcut_text, R.id.cb_shortcut_check });
		lv.setAdapter(adapter);
		// lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				listItem.remove(position);
				CheckBox cb = (CheckBox) view.findViewById(R.id.cb_shortcut_check);
				if (cb.isChecked()) {
					cb.setChecked(false);
					listItem.add(position, false);
				} else {
					cb.setChecked(true);
					listItem.add(position, true);
				}
			}

		});

		Button btn_sure = (Button) viewDialog.findViewById(R.id.sure_btn);
		Button btn_cancle = (Button) viewDialog.findViewById(R.id.cancel_btn);

		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 生成所选项的快捷方式
				createShortCut();
				builder.dismiss();
			}
		});

		btn_cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				builder.dismiss();
			}
		});

	}

	/** 生成对话框 **/
	private void createShortCut() {
		for (int i = 0; i < listItem.size(); i++) {
			if (!listItem.get(i)) {
				continue;
			}
			Intent intent = null;
			Intent short_intent = null;
			Parcelable icon = null;
			short_intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
			switch (i) {
			case 0:
				intent = new Intent(this, NewWriteActivity.class);
				// 设置快捷方式name
				short_intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "文字笔记");
				// 设置icon
				icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.shortcut_notes);
				
				break;

			case 1:
				intent = new Intent(this, HandWritingActivity.class);
				// 设置快捷方式name
				short_intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "手写笔记");
				// 设置icon
                icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.shortcut_hand);
				break;

			case 2:
				intent = new Intent(this, NewRecordActivity.class);
				// 设置快捷方式name
				short_intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "录音笔记");
				// 设置icon
				icon = Intent.ShortcutIconResource.fromContext(this,R.drawable.shortcut_record);
				break;

			case 3:
				intent = new Intent(this, NewPaintActivity.class);
				// 设置快捷方式name
				short_intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "涂鸦笔记");
				// 设置icon
				icon = Intent.ShortcutIconResource.fromContext(this,R.drawable.shortcut_paint);
				break;
			}
			
			short_intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
			// 不重复生成快捷方式
			short_intent.putExtra("duplicate", false);
			short_intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
					intent);
			sendBroadcast(short_intent);
		}
	}

	/** 摇动触发事件 **/
	private class shakeLitener implements OnShakeListener {
		@Override
		public void onShake() {
			Intent intent = new Intent(SettingActivity.this,
					NewWriteActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_left_out);
		}
	}

	/** 滑动开关按钮事件监听 **/
	@Override
	public void OnChanged(boolean CheckState) {
		if (CheckState) {
			Toast.makeText(SettingActivity.this, "已开启！摇摇手机试试",
					Toast.LENGTH_LONG).show();
			// 绑定监听器，之后可以检测加速度传感器
			mShakeListener.setOnShakeListener(new shakeLitener());
			mShakeListener.start(); // 开启重力感应(注册服务)
		} else {
			Toast.makeText(SettingActivity.this, "已关闭！", Toast.LENGTH_SHORT).show();
			mShakeListener.stop();// （解除服务）
		}
		mCheckState = CheckState;
	}
	
	/** 返回键监听 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			Intent intent4=new Intent(this,MainActivity.class);
			startActivity(intent4);
			finish();
			overridePendingTransition(R.anim.alpha_in,R.anim.scale_suoxiao_out
					);
		}
		return super.onKeyDown(keyCode, event);
	}
}
